import logging
import os
import json
from service.personal_center.personalservice import PersonalService
from service.account_deal.account_deal_service import AccountDealService
from service.account_rent.account_rent_service import AccountRentService
from service.good_manager.game_manager_service import GameManagerService
from service.advance_order.service import AdvanceOrderService
from flask_session import Session
from flask_jwt_extended import JWTManager
from datetime import timedelta
from flask_cors import CORS
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64

service_dict = {
    "personal_service": PersonalService,
    "account_deal_service": AccountDealService,
    "account_rent_service": AccountRentService,
    "game_manager_service": GameManagerService,
    "advance_order_service": AdvanceOrderService
}

SECRET_KEY = b'1234567890654321'
IV = b'abcdefghijklmnop'


class Builder:
    def __init__(self, app) -> None:
        self.app = app

    def __getattr__(self, func):
        if hasattr(self.app, func):
            return getattr(self.app, func)
        raise AttributeError(f"'{self.__class__.__name__}' has no attribute '{func}'")

    def encrypt_data(self, data):
        cipher = AES.new(SECRET_KEY, AES.MODE_CBC, IV)
        padded_data = pad(json.dumps(data).encode('utf-8'), AES.block_size)
        encrypted_bytes = cipher.encrypt(padded_data)
        encrypted_base64 = base64.b64encode(encrypted_bytes).decode('utf-8')
        return encrypted_base64    

    def init_log(self):
        logging.basicConfig(level=logging.INFO)

    def init_service(self, service_name):
        service_dict[service_name](self.app)

    def set_proxy(self):
        CORS(self.app)

    def set_session(self):
        # 配置session
        self.config["SECRET_KEY"] = os.urandom(24)
        self.config["SESSION_TYPE"] = "filesystem"
        self.config["PERMANENT_SESSION_LIFETIME"] = timedelta(seconds=10)
        Session(self.app)

    def set_jwt(self):
        # 配置token
        self.config['JWT_SECRET_KEY'] = "baibai"
        # 应该使用难以猜测的密钥
        # 设置Token超期时间，例如设置为1小时
        self.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=365)
        JWTManager(self.app)

    def set_request(self):
        @self.after_request
        def after_request(response):
            if response.status_code == 200:
                data = response.get_json()
                data = self.encrypt_data(data)
                response.set_data(json.dumps({"data": data}).encode('utf-8'))
            response.headers.add('Access-Control-Allow-Origin', '*')
            response.headers.add(
                'Access-Control-Allow-Headers', 'Content-Type,Authorization')
            response.headers.add(
                'Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
            return response        
        

    def build(self, service_name):
        self.init_log()
        self.set_proxy()
        self.set_request()
        self.set_jwt()
        self.init_service(service_name)